package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author EvenYuan
 */
public class CarBusinessRealm extends AuthorizingRealm {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 获取当前登录的用户
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        if (employee.isAdmin()){
            info.addRole("admin");
            //权限通配符，表示拥有所有的权限，例如 employee:list  *:* 代表拥有所有的权限
            info.addStringPermission("*:*");
        }else{
            //根据用户的id查询该用户拥有的角色编码
            List<String> roles = roleService.getRoleNamesByEmployeeId(employee.getId());
            roles.forEach(System.out::println);
            info.addRoles(roles);
            //根据用户的id查询该用户拥有的权限表达式
            List<String> permissions = permissionService.selectByEmpId(employee.getId());
            info.addStringPermissions(permissions);
        }
        //info对象中有哪些角色和权限，就代表当前登录用户拥有哪些角色和权限
        return info;
    }

    /**
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Employee employee = employeeService.selectByUsername(username);
        if (employee!=null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    employee,
                    employee.getPassword(),
                    this.getName());
            return info;
        }
        else {
            return null;
        }
    }
}
